package weeks;

/**
 * GCalendarServices: this will gather data from users Google apps. 
 * Currently supported is calendar, but other services will be added. 
 * The gdata java API is used in earnest here.
 * 
 * @author - Owen Phelan
 */

import com.google.gdata.client.*;
import com.google.gdata.data.*;

import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.calendar.*;
import com.google.api.gbase.client.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JOptionPane;


public class GCalendarServices {
	
	/**
	 * Public variables
	 */
	public static String username;
	public static String pass;
	public static String myEntryTitle;
	public static String loginStart = "Logging in....";
	public static String loginComplete = "Login Complete!";
	public static CalendarEventEntry entry;
	public static int calendarCount = 0;
	public static int eventCount = 0;
	public static int toddaysCount = 0;
	public static int[] participantEventSize;
	public static CalendarService myService;
	public static List<When> events;
	
	public GCalendarServices(){
		super();
	}
	
	/**
	 * Main method
	 * @param args
	 */
    public static void main(String[] args) {
    	//username = JOptionPane.showInputDialog(null, "enter username");
		//pass = JOptionPane.showInputDialog(null, "enter pass");
		//calendarServices(username, pass);
    }
	
	/**
	 * Calendar Services - first attempt
	 */
	public static void calendarServices(String user, String password){
	
	try{
		 	// Uses a URL modified with the username, logs in and gathers the information in the form of a list
			// Note, as of yet, this only gathers information from your default calendar
		
			System.setProperty("https.proxyHost", "proxy4.ucd.ie");
			System.setProperty("https.proxyPort", "8484");
			
			System.out.println(loginStart);
	        myService = new CalendarService("Weeks - Google Calendar");
	        myService.setUserCredentials(user, password);
	        URL feedUrl = new URL("http://www.google.com/calendar/feeds/"+user+"@gmail.com/private/full");
	        System.out.println(loginComplete); 
	        System.out.println();
	        
	        
	        //Gather all calendars
	        URL feedUrl2 = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");
	        CalendarFeed resultFeed2 = myService.getFeed(feedUrl2, CalendarFeed.class);
	            
	        System.out.println("All of your calendars:");
	        System.out.println();
	        
	        for (int i = 0; i < resultFeed2.getEntries().size(); i++) {
	          CalendarEntry entry = resultFeed2.getEntries().get(i);
	          System.out.println(entry.getTitle().getPlainText());
	          System.out.println("Summary: "+entry.getSummary());
	          System.out.println("Color:" + entry.getColor());
	          System.out.println("ID:" + entry.getId());
	          calendarCount = i+1;
	          
	          System.out.println();
	        }
	        
	        System.out.println();
			   
	        //Gather events + times from personal calendar
	        CalendarEventFeed resultFeed = myService.getFeed(feedUrl, CalendarEventFeed.class);
	        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
	        
		    eventCount = i+1;
		    entry = resultFeed.getEntries().get(i);
		    System.out.println(eventCount+": "+entry.getTitle().getPlainText());
		          
		    //Gather events in the form of a list, 'When' is elemental to the calendar API, apparently
		    events = entry.getTimes();
		    for (When x:events) {
		        
		    	System.out.println();  
		    	List<EventWho> PL = entry.getParticipants();
		    	EventWho[] ew = PL.toArray(new EventWho[PL.size()]);
		    	System.out.println(ew[0].toString());
		    	
		    	//participantEventSize[i] = entry.getParticipants().size();
		    	System.out.println("RunJustViz: "+x.getStartTime()+"\n"+"End: "+x.getEndTime());
		    	System.out.println("Participants: "+entry.getParticipants());
		        System.out.println("Number of Participants: "+entry.getParticipants().size());
		        System.out.println();  
		     }
	        }
	        
	        //Query to retrieve recent events
	        Query q = new Query(feedUrl);
	        Query today = new Query(feedUrl);
	        q.getMaxResults();
	        DateTime x = today.getUpdatedMax();
	        
	        //put query into a feed
	        Feed myResultsFeed = myService.query(q, Feed.class);
	        //if there are entries
	        if (myResultsFeed.getEntries().size() > 0) {
	             Entry firstMatchEntry = myResultsFeed.getEntries().get(0);
	             myEntryTitle = firstMatchEntry.getTitle().getPlainText();
	             System.out.println(myEntryTitle);
	             System.out.println("Calendar Info:\n" + eventCount + " Events\n");
	        }else{
	        	System.out.println("There are no entries in your calendar\n");
	        }
		
	    //Exception handling
    	} catch (MalformedURLException e) {
            System.out.println("Invalid URL");
        } catch (IOException e) {
            System.out.println("Unable to execute");
        } catch (AuthenticationException e){
        	System.out.println("Authentication Problem");
        } catch (ServiceException e){
        	System.out.println("Service Problem"); 
        }
    }

   
    /**
     * Returns the list of events
     * TODO: make it so that it detects how many events 
     * there are within the next few days
     * @return
     */
	public List<When> getEvents(){
		return events;
	}
	
    /**
     * Returns todays events
     */
	public int getTodaysEvents(){
		

		return 0;
	}
	
	/**
	 * Returns the number of Participants for each event
	 * @return
	 */
	public int getNumOfParticipants(){
		return 0;
	}
	
	/**
	 * Returns the number of Calendars the user is subscribed to
	 * @return
	 */
	public int getNumberOfCals(){
		return calendarCount;
	}
	
    /**
     * Returns the amount of events in your calendar 
     * @return
     */
	public int getNumberOfEvents(){
		return eventCount;
	}
	
	/**
	 * Returns some/all of the events in the calendar in question
	 * TODO: make it so that it only shows the up-coming events
	 * @return
	 */
	public String getRecentEvent(){
		return myEntryTitle;
	}
	
	/**
	 * Returns user details, if needed in the visualisation 
	 * or proposed 
	 * @return
	 */
	public String getUserDetails(){
		return username;
	}
	
	/**
	 * Returns the version of the GoogleService
	 * @return
	 */
	public String getGSVersion(){
		return myService.getVersion().toString();
	}
	
	public String getCalendarURL(){
		return myService.CALENDAR_ROOT_URL;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		GCalendarServices.username = username;
	}

	public void setPass(String pass) {
		GCalendarServices.pass = pass;
	}
}